# encoding: utf-8
# Copyright 2012, Google Inc. All Rights Reserved.
"""
State serving handler. Gets and sets internal state
"""
__author__ = 'davidthorpe@google.com'

import sys,os,logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

# import local libraries
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import constants, cache

# Create cache
state_cache = cache.StateCache()

class FileNotFound(Exception):
	pass

class StateJSHandler(webapp.RequestHandler):
	def set_nocache(self):
		self.response.headers["Pragma"]= "no-cache"
		self.response.headers["Cache-Control"]="no-cache"
		self.response.headers["Expires"]="Thu, 01 Dec 1994 16:00:00"
	
	def get(self):
		try:
			self.response.headers['Content-Type'] = "application/javascript"
			self.set_nocache()
			json = state_cache.get_state_json()
			if json:
				self.response.out.write(json)
				self.response.out.write("\r\n")
			else:
				raise Exception("Unable to retrieve state")
		except FileNotFound, e:
			self.error(404)
			self.response.headers['Content-Type'] = "text/plain"
			self.response.out.write("Resource not found: %s\n\n" % e)
		except Exception, e:
			self.error(500)
			self.response.headers['Content-Type'] = "text/plain"
			self.response.out.write("Server Error: %s\n\n" % e)

class StateHandler(webapp.RequestHandler):
	def set_nocache(self):
		self.response.headers["Pragma"]= "no-cache"
		self.response.headers["Cache-Control"]="no-cache"
		self.response.headers["Expires"]="Thu, 01 Dec 1994 16:00:00"
	
	def get(self,name,index):
		try:
			# GET requests can only be for (name) not (index)
			if index:
				raise FileNotFound("%s" % self.request.url)
			# Retrieve the value
			value = state_cache.get_state_value(name)
			if value==None:
				raise FileNotFound("%s" % self.request.url)
			# return the value
			self.response.headers['Content-Type'] = "application/javascript"
			self.set_nocache()
			self.response.out.write(value)
			self.response.out.write("\r\n")
		except FileNotFound, e:
			self.error(404)
			self.response.headers['Content-Type'] = "text/plain"
			self.response.out.write("Resource not found: %s\n\n" % e)
		except Exception, e:
			self.error(500)
			self.response.headers['Content-Type'] = "text/plain"
			self.response.out.write("Server Error: %s\n\n" % e)
	def put(self,name,index):
		try:
			# PUT requests can only be for (name,index)
			if not index:
				raise FileNotFound("%s" % self.request.url)
			else:
				index = long(index)
			name = unicode(name)
			# Set the cache value
			value = state_cache.set_state_value(name,index)
			if value==None:
				raise FileNotFound("%s" % self.request.url)
			# return the value
			self.response.headers['Content-Type'] = "application/javascript"
			self.set_nocache()
			self.response.out.write(value)
			self.response.out.write("\r\n")
		except FileNotFound, e:
			self.error(404)
			self.response.headers['Content-Type'] = "text/plain"
			self.response.out.write("Resource not found: %s\n\n" % e)
#		except Exception, e:
#			self.error(500)
#			self.response.headers['Content-Type'] = "text/plain"
#			self.response.out.write("Server Error: %s\n\n" % e)
		

application = webapp.WSGIApplication([
	(r'/state.js',StateJSHandler),
	(r'/state/(\w+)/?(\d*)',StateHandler)
],debug=constants.DEBUG)

def main():
	if constants.DEBUG:
		logging.getLogger().setLevel(logging.DEBUG)
	else:
		logging.getLogger().setLevel(logging.INFO)
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
